package com.happy3w.cmds;

import com.happy3w.cmds.command.AppCmd;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@SpringBootApplication
public class CmdApp implements CommandLineRunner {

    private final Map<String, AppCmd> cmds;

    public CmdApp(List<AppCmd> cmds) {
        this.cmds = cmds.stream().collect(Collectors.toMap(AppCmd::getName, cmd -> cmd));
    }

    @Override
    public void run(String... args) throws Exception {
        List<String> arguments = new ArrayList<>(Arrays.asList(args));
        log.info("Current Args:{}", arguments);
        if (arguments.size() < 1) {
            System.out.println("Need cmd:");
            printAllCmds();
            return;
        }

        String cmdName = arguments.get(0);
        arguments.remove(0);

        AppCmd cmd = cmds.get(cmdName);
        if (cmd == null) {
            System.out.println("Unsupported cmd:" + cmdName);
            printAllCmds();
            return;
        }

        cmd.run(arguments);
    }

    private void printAllCmds() {
        cmds.values().forEach(cmd -> {
            System.out.println(cmd.getName());
        });
    }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(CmdApp.class);
        app.setWebApplicationType(WebApplicationType.NONE);
        app.run(args);
    }
}
